package com.dxy.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dxy.common.dto.UserDTO;
import com.dxy.common.exp.ServiceException;
import com.dxy.common.pojo.Resource;
import com.dxy.common.pojo.Role;
import com.dxy.common.pojo.User;
import com.dxy.common.user.UserContextHolder;
import com.dxy.common.utils.MD5Util;
import com.dxy.common.vo.Result;
import com.dxy.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RefreshScope // nacos配置自动刷新，另外外需设置refresh为true才能生效
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${dxy.test:123456}")
    private String test;

    @GetMapping("/test")
    public Result test(String id) {
        if ("1".equals(id)) {
            throw new ServiceException("aaa");
        }
        return Result.ok(test);
    }

    @PostMapping("/createUser")
    public Result<User> createUser(@RequestBody UserDTO userDTO) {
        log.info("测试创建用户:{}", userDTO);
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(MD5Util.getEncryptPassword(userDTO.getPassword()));
        user.setStatus(0);
        userService.save(user);
        return Result.ok(user);
    }

    @GetMapping("/deleteUser/{userId}")
    public Result deleteUser(@PathVariable("userId") Integer userId) {
        System.out.println("当前用户：" + UserContextHolder.getAuthUserSubject().user());
        System.out.println("用户分组：" + UserContextHolder.getAuthUserSubject().groups());
        System.out.println("用户角色：" + UserContextHolder.getAuthUserSubject().roles());
        userService.removeById(userId);
        return Result.ok();
    }

    @GetMapping("/findUserByUserId/{userId}")
    public Result<User> findById(@PathVariable("userId") Integer userId) {
        User user = userService.getById(userId);
        return Result.ok(user);
    }

    @GetMapping("/findUserByUserName/{userName}")
    public Result<User> findByUsername(@PathVariable("userName") String userName) {
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, userName));
        return Result.ok(user);
    }


}
